package com.metis.document.parse.dialog.utils;

import com.metis.document.parse.dialog.enums.FileTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.slf4j.MDC;

import java.io.File;
import java.io.IOException;
import java.lang.ref.Cleaner;
import java.nio.file.Path;
import java.util.Map;
import java.util.UUID;


@Slf4j
public class AutoCleanFile extends File {
    private static final Cleaner cleaner = Cleaner.create();
    private final static String TMP_FILE_PREFIX = "parse.temp_";
    private static final String tmpdir = System.getProperty("java.io.tmpdir");
    private static final long serialVersionUID = 1L;

    public AutoCleanFile(@NotNull FileTypeEnum fileType) {
        super(createTempFile(fileType));
        Path path = toPath();
        Map<String, String> mdcMap= MDC.getCopyOfContextMap();
        cleaner.register(this, () -> {
            //备份MDC用于还原
            Map<String, String> backup = MDC.getCopyOfContextMap();
            boolean delete = path.toFile().delete();
            MDC.setContextMap(mdcMap);
            log.debug("delete temp File [{}]: {}", delete, path);
            MDC.setContextMap(backup);
        });
    }
    private static String createTempFile(@NotNull FileTypeEnum fileType) {
        try {
            String path = Path.of(tmpdir, String.format("%s%s.%s", TMP_FILE_PREFIX, UUID.randomUUID(), fileType.getType())).toString();
            boolean newFile = new File(path).createNewFile();
            log.info("create temp File [{}]: {}", newFile, path);
            return path;
        } catch (IOException e) {
            //出现未知异常，直接抛出
            //理论上不应该进入这里
            throw new IllegalStateException(e);
        }
    }

    public static AutoCleanFile build(@NotNull FileTypeEnum fileType){
        return new AutoCleanFile(fileType);
    }
}
